package threadcoreknowledge.stopthreads.volatiledemo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 生产者生产快速，消费者速度慢
 * 所以队列满了之后，生产者会阻塞，等待消费者消费
 * 正确中断
 */
public class WrongWayVolatileFixed {
    public static void main(String[] args) throws InterruptedException {
        WrongWayVolatileFixed body = new WrongWayVolatileFixed();
        ArrayBlockingQueue<Integer> storage = new ArrayBlockingQueue<Integer>(10);
        Producer producer = body.new Producer(storage);
        Thread producerThread = new Thread(producer);
        producerThread.start();

        Consumer consumer = body.new Consumer(storage);
        while (consumer.needMoreNums()) {
            System.out.println(consumer.getStorage().take() + "已经被消费");
            Thread.sleep(100);
        }
        System.out.println("消费者不需要更多数据了");
        // 停止生产数据
        producerThread.interrupt();
    }
    class Producer implements Runnable {
        private BlockingQueue<Integer> storage;

        public Producer(BlockingQueue<Integer> storage) {
            this.storage = storage;
        }

        @Override
        public void run() {
            int num = 0;
            try {
                while (num <= 10000 && !Thread.currentThread().isInterrupted()) {
                    if (num % 100 == 0) {
                        System.out.println(num + "是100的倍数，被放到仓库了");
                        storage.put(num);
                    }
                    num++;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("生产者停止运行");
            }
        }
    }

    class Consumer {
        private BlockingQueue storage;

        public Consumer(BlockingQueue storage) {
            this.storage = storage;
        }

        public boolean needMoreNums() {
            System.out.println(Math.random());
            return !(Math.random() > 0.95);
        }

        public BlockingQueue getStorage() {
            return storage;
        }
    }
}

